package com.lzy.elasticsearch.config;


import com.lzy.elasticsearch.template.ElasticsearchServiceTemplate;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnClass(RestHighLevelClient.class)
@EnableConfigurationProperties({ElasticsearchClientProperty.class})
@ConditionalOnProperty(name = "com.lzy.elasticsearch.client.enabled", havingValue = "true")
public class ElasticsearchClientAutoConfig {

    @Autowired
    private ElasticsearchClientProperty property;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        // 获取配置好的ip，端口，等信息
        HttpHost[] httpHosts = property.getProperties().stream()
                .map(o -> new HttpHost(o.getHostname(), o.getPort(), o.getScheme()))
                .toArray(HttpHost[]::new);
        // 获取账号密码登录凭据
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(property.getUsername(), property.getPassword()));
        // 创建一个客户端，把配置信息和凭据放进去
        RestClientBuilder builder = RestClient.builder(httpHosts);
        builder.setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.disableAuthCaching();
            return httpClientBuilder.setDefaultCredentialsProvider(provider);
        });
        // 超时时间也放进去
        builder.setRequestConfigCallback(requestConfigBuilder -> {
            requestConfigBuilder.setConnectTimeout(property.getConnectTimeout());
            requestConfigBuilder.setSocketTimeout(property.getSocketTimeout());
            return requestConfigBuilder;
        });
        return new RestHighLevelClient(builder);
    }

    @Bean
    public ElasticsearchServiceTemplate elasticsearchServiceTemplate() {
        return new ElasticsearchServiceTemplate();
    }

    /*@Bean
    public IndicesClient indicesClient(RestHighLevelClient client) {
        return client.indices();
    }*/
}
